package com.clkj.goldpartner.filter;

import com.alibaba.fastjson.JSON;
import com.clkj.goldpartner.pojo.common.JwtUtil;
import com.clkj.goldpartner.pojo.common.Result;
import com.clkj.goldpartner.pojo.common.StatusCode;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //添加这行代码，让OPTIONS请求通过
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        //从header中获取token
        String token = request.getHeader("Authorization");
        //token为空
        if (StringUtils.isEmpty(token)) {
//            setCorsMappings(request, response);
//            throw new XjxccException("登录信息不存在，请重新登录", 601);
            returnJson(response);
            return false;
        }
        //boolean true：令牌在头文件中  false:令牌不在头文件中--》将令牌春如头文件中，再传递给其他为服务
        //boolean hasToken = true;
        try {
            JwtUtil.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            // throw new XjxccException("登录信息不存在，请重新登录", 601);
            returnJson(response);
            return false;
        }
        return true;
    }

    // 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    // 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {

    }

    //    private void setCorsMappings(HttpServletRequest request, HttpServletResponse response){
//        String origin = request.getHeader("Origin");
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
//        response.setHeader("Access-Control-Max-Age", "3600");
//        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//    }
    private void returnJson(HttpServletResponse response) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(new Result(false, StatusCode.LOGINERROR, "登录信息有误或登录已过期")));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
